package controller

import (
	"digital/server/common"
	"digital/server/model"
	"digital/server/response"
	"github.com/gin-gonic/gin"
	"log"
	"math"
	"net/http"
	"strconv"
)

// 校团委端查看所有年检评优记录
func GetAS_CE(c *gin.Context) {
	DB := common.GetDB()
	var ces []model.IssueCE
	err := DB.Table("issue_ce").Where("State=?", 1).Find(&ces).Error
	if err != nil {
		response.Response(c, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("Error querying user:", err)
		return
	}

	var ce_clubInfo [][]model.Club //每年评优没完成的社团
	var ce_ratio []float64
	var ce_Names []string
	var ce_files []model.AllFile
	for _, ce := range ces {
		//获得所有评优的发布人姓名
		var user model.User
		err := DB.Table("users").Where("uid = ?", ce.Publisher).Find(&user).Error
		if err != nil {
			log.Println("Error querying user:", err)
			return
		}
		ce_Names = append(ce_Names, user.Uname)

		//获得所有评优的文件
		var allfile model.AllFile
		err = DB.Table("all_file").Where("id = ?", ce.ATID).Find(&allfile).Error
		if err != nil {
			log.Println("Error querying file:", err)
			return
		}
		ce_files = append(ce_files, allfile)

		//获得所有的评优记录
		var ceApply []model.Apply_CE
		err1 := DB.Table("apply_ce").Where("CEid = ? and state=?", ce.CEID, 1).Find(&ceApply).Error
		if err1 != nil {
			log.Println("Error querying apply_ce:", err1)
			return
		}

		//获得评优申请审批通过的社团id
		var applyId []int
		for _, apply := range ceApply {
			applyId = append(applyId, apply.CID)
		}

		//获得评优年份所有社团的id
		year := ce.Year
		var clubs []model.Club
		var totalID []int
		err = DB.Table("clubs").Where("YEAR(Edate) <= ? AND (YEAR(Odate) >= ? OR Odate IS NULL) and exist!=?", year, year, 0).Find(&clubs).Error
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "查询社团数据失败"})
			return
		}
		for _, club := range clubs {
			totalID = append(totalID, club.Cid)
		}

		//获取评优完成度
		var ratio float64
		if len(totalID) == 0 {
			ratio = 0
		} else {
			ratio = float64(len(applyId)) / float64(len(totalID))
		}
		ce_ratio = append(ce_ratio, math.Round(ratio*100)/100)

		//获得没有申请评优的社团id
		var diff []int
		applyMap := make(map[int]bool)
		for _, id := range applyId {
			applyMap[id] = true
		}
		for _, id := range totalID { // 遍历totalID，如果元素不在applyMap中，则添加到diff中
			if _, exists := applyMap[id]; !exists {
				diff = append(diff, id)
			}
		}

		//获取未完成的社团信息
		var n_clubs []model.Club
		for _, id := range diff {
			var club model.Club
			err := DB.Table("clubs").Where("id = ?", id).Find(&club).Error
			if err != nil {
				log.Println("Error querying club:", err)
				continue
			}
			n_clubs = append(n_clubs, club)
		}
		ce_clubInfo = append(ce_clubInfo, n_clubs)
	}

	var ass []model.IssueAS
	err2 := DB.Table("issue_as").Where("State=?", 1).Find(&ass).Error
	if err2 != nil {
		response.Response(c, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("Error querying user:", err2)
		return
	}

	var as_clubInfo [][]model.Club //每年年检没完成的社团
	var as_ratio []float64
	var as_Names []string
	var as_files []model.AllFile

	for _, as := range ass {
		//获得所有评优的发布人姓名
		var user model.User
		err := DB.Table("users").Where("uid = ?", as.Publisher).Find(&user).Error
		if err != nil {
			log.Println("Error querying user:", err)
			return
		}
		as_Names = append(as_Names, user.Uname)

		//获得所有评优的文件
		var allfile model.AllFile
		err = DB.Table("all_file").Where("id = ?", as.ATID).Find(&allfile).Error
		if err != nil {
			log.Println("Error querying file:", err)
			return
		}
		as_files = append(as_files, allfile)

		//获得所有的年检记录
		var asApply []model.Apply_AS
		err2 := DB.Table("apply_as").Where("CPid = ? and state=?", as.CPID, 1).Find(&asApply).Error
		if err2 != nil {
			log.Println("Error querying apply_ae:", err2)
			return
		}

		//获得年检申请审批通过的社团id
		var as_applyId []int
		for _, apply := range asApply {
			as_applyId = append(as_applyId, apply.CID)
		}

		//获得年检年份所有社团的id
		year := as.Year
		var as_clubs []model.Club
		var as_totalID []int

		err = DB.Table("clubs").Where("YEAR(Edate) <= ? AND (YEAR(Odate) >= ? OR Odate IS NULL) and exist!=?", year, year, 0).Find(&as_clubs).Error
		if err != nil {
			c.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "查询社团数据失败"})
			return
		}
		for _, club := range as_clubs {
			as_totalID = append(as_totalID, club.Cid)
		}

		//获取年检完成度
		var ratio float64
		if len(as_totalID) == 0 {
			ratio = 0
		} else {
			ratio = float64(len(as_applyId)) / float64(len(as_totalID))
		}
		as_ratio = append(as_ratio, math.Round(ratio*100)/100)

		//获得没有申请年检的社团id
		var as_diff []int
		applyMap := make(map[int]bool)
		for _, id := range as_applyId {
			applyMap[id] = true
		}
		for _, id := range as_totalID { // 遍历totalID，如果元素不在applyMap中，则添加到diff中
			if _, exists := applyMap[id]; !exists {
				as_diff = append(as_diff, id)
			}
		}

		//获取未完成的社团信息
		var n_clubs []model.Club
		for _, id := range as_diff {
			var club model.Club
			err := DB.Table("clubs").Where("id = ?", id).Find(&club).Error
			if err != nil {
				log.Println("Error querying club:", err)
				continue
			}
			n_clubs = append(n_clubs, club)
		}
		as_clubInfo = append(as_clubInfo, n_clubs)
	}
	response.Response(c, http.StatusOK, 200, gin.H{"ces": ces, "ass": ass, "ce_clubInfo": ce_clubInfo,
		"as_clubInfo": as_clubInfo, "ce_ratio": ce_ratio, "as_ratio": as_ratio, "ce_Names": ce_Names, "as_Names": as_Names, "ce_files": ce_files, "as_files": as_files}, "查询成功")
}

func DeletedCERecord(ctx *gin.Context) {
	Ceid := ctx.Query("index")
	ceid, _ := strconv.Atoi(Ceid)

	DB := common.GetDB()
	err0 := DB.Exec("UPDATE issue_ce SET State= ? WHERE CEID=?", 0, ceid).Error
	if err0 != nil {
		log.Println("err:", err0)
		response.Response(ctx, http.StatusBadRequest, 422, nil, "修改失败，请重试！")
		return
	}

	var ces []model.IssueCE
	err := DB.Table("issue_ce").Where("State=?", 1).Find(&ces).Error
	if err != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("Error querying user:", err)
		return
	}

	var ce_clubInfo [][]model.Club //每年评优没完成的社团
	var ce_ratio []float64
	var ce_Names []string
	var ce_files []model.AllFile
	for _, ce := range ces {
		//获得所有评优的发布人姓名
		var user model.User
		err := DB.Table("users").Where("uid = ?", ce.Publisher).Find(&user).Error
		if err != nil {
			log.Println("Error querying user:", err)
			return
		}
		ce_Names = append(ce_Names, user.Uname)

		//获得所有评优的文件
		var allfile model.AllFile
		err = DB.Table("all_file").Where("id = ?", ce.ATID).Find(&allfile).Error
		if err != nil {
			log.Println("Error querying file:", err)
			return
		}
		ce_files = append(ce_files, allfile)

		//获得所有的评优记录
		var ceApply []model.Apply_CE
		err1 := DB.Table("apply_ce").Where("CEid = ? and state=?", ce.CEID, 1).Find(&ceApply).Error
		if err1 != nil {
			log.Println("Error querying apply_ce:", err1)
			return
		}

		//获得评优申请审批通过的社团id
		var applyId []int
		for _, apply := range ceApply {
			applyId = append(applyId, apply.CID)
		}

		//获得评优年份所有社团的id
		year := ce.Year
		var clubs []model.Club
		var totalID []int
		err = DB.Table("clubs").Where("YEAR(Edate) <= ? AND (YEAR(Odate) >= ? OR Odate IS NULL) and exist!=?", year, year, 0).Find(&clubs).Error
		if err != nil {
			ctx.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "查询社团数据失败"})
			return
		}
		for _, club := range clubs {
			totalID = append(totalID, club.Cid)
		}

		//获取评优完成度
		var ratio float64
		if len(totalID) == 0 {
			ratio = 0
		} else {
			ratio = float64(len(applyId)) / float64(len(totalID))
		}
		ce_ratio = append(ce_ratio, math.Round(ratio*100)/100)

		//获得没有申请评优的社团id
		var diff []int
		applyMap := make(map[int]bool)
		for _, id := range applyId {
			applyMap[id] = true
		}
		for _, id := range totalID { // 遍历totalID，如果元素不在applyMap中，则添加到diff中
			if _, exists := applyMap[id]; !exists {
				diff = append(diff, id)
			}
		}

		//获取未完成的社团信息
		var n_clubs []model.Club
		for _, id := range diff {
			var club model.Club
			err := DB.Table("clubs").Where("id = ?", id).Find(&club).Error
			if err != nil {
				log.Println("Error querying club:", err)
				continue
			}
			n_clubs = append(n_clubs, club)
		}
		ce_clubInfo = append(ce_clubInfo, n_clubs)
	}
	response.Response(ctx, http.StatusOK, 200, gin.H{"ces": ces, "ce_clubInfo": ce_clubInfo, "ce_ratio": ce_ratio, "ce_Names": ce_Names, "ce_files": ce_files}, "查询成功")
}

func DeletedASRecord(ctx *gin.Context) {
	Cpid := ctx.Query("index")
	cpid, _ := strconv.Atoi(Cpid)

	DB := common.GetDB()
	err0 := DB.Exec("UPDATE issue_as SET State= ? WHERE CPID=?", 0, cpid).Error
	if err0 != nil {
		log.Println("err:", err0)
		response.Response(ctx, http.StatusBadRequest, 422, nil, "修改失败，请重试！")
		return
	}

	var ass []model.IssueAS
	err2 := DB.Table("issue_as").Where("State=?", 1).Find(&ass).Error
	if err2 != nil {
		response.Response(ctx, http.StatusBadRequest, 400, nil, "发生错误，请重试")
		log.Println("Error querying user:", err2)
		return
	}

	var as_clubInfo [][]model.Club //每年年检没完成的社团
	var as_ratio []float64
	var as_Names []string
	var as_files []model.AllFile

	for _, as := range ass {
		//获得所有评优的发布人姓名
		var user model.User
		err := DB.Table("users").Where("uid = ?", as.Publisher).Find(&user).Error
		if err != nil {
			log.Println("Error querying user:", err)
			return
		}
		as_Names = append(as_Names, user.Uname)

		//获得所有评优的文件
		var allfile model.AllFile
		err = DB.Table("all_file").Where("id = ?", as.ATID).Find(&allfile).Error
		if err != nil {
			log.Println("Error querying file:", err)
			return
		}
		as_files = append(as_files, allfile)

		//获得所有的年检记录
		var asApply []model.Apply_AS
		err2 := DB.Table("apply_as").Where("CPid = ? and state=?", as.CPID, 1).Find(&asApply).Error
		if err2 != nil {
			log.Println("Error querying apply_ae:", err2)
			return
		}

		//获得年检申请审批通过的社团id
		var as_applyId []int
		for _, apply := range asApply {
			as_applyId = append(as_applyId, apply.CID)
		}

		//获得年检年份所有社团的id
		year := as.Year
		var as_clubs []model.Club
		var as_totalID []int

		err = DB.Table("clubs").Where("YEAR(Edate) <= ? AND (YEAR(Odate) >= ? OR Odate IS NULL) and exist!=?", year, year, 0).Find(&as_clubs).Error
		if err != nil {
			ctx.JSON(http.StatusBadRequest, gin.H{"code": 400, "message": "查询社团数据失败"})
			return
		}
		for _, club := range as_clubs {
			as_totalID = append(as_totalID, club.Cid)
		}

		//获取年检完成度
		var ratio float64
		if len(as_totalID) == 0 {
			ratio = 0
		} else {
			ratio = float64(len(as_applyId)) / float64(len(as_totalID))
		}
		as_ratio = append(as_ratio, math.Round(ratio*100)/100)

		//获得没有申请年检的社团id
		var as_diff []int
		applyMap := make(map[int]bool)
		for _, id := range as_applyId {
			applyMap[id] = true
		}
		for _, id := range as_totalID { // 遍历totalID，如果元素不在applyMap中，则添加到diff中
			if _, exists := applyMap[id]; !exists {
				as_diff = append(as_diff, id)
			}
		}

		//获取未完成的社团信息
		var n_clubs []model.Club
		for _, id := range as_diff {
			var club model.Club
			err := DB.Table("clubs").Where("id = ?", id).Find(&club).Error
			if err != nil {
				log.Println("Error querying club:", err)
				continue
			}
			n_clubs = append(n_clubs, club)
		}
		as_clubInfo = append(as_clubInfo, n_clubs)
	}
	response.Response(ctx, http.StatusOK, 200, gin.H{"ass": ass, "as_ratio": as_ratio, "as_Names": as_Names, "as_files": as_files}, "查询成功")
}
